


import com.example.studentknowledgesys.config.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @author 光的代言人
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handleNotFound(NoHandlerFoundException ex) {
        return Result.error(HttpStatus.NOT_FOUND.value(), "资源未找到，可能是请求路径错误，请检查！");
    }
    @ExceptionHandler({HttpMessageNotReadableException.class, MethodArgumentNotValidException.class})
    public Result handleBadRequest(Exception ex) {
        return Result.error(HttpStatus.BAD_REQUEST.value(), "请求参数错误或参数类型不匹配，请检查！");
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result handleMethodNotSupported(HttpRequestMethodNotSupportedException ex) {
        // 返回自定义的错误消息
        return Result.error(HttpStatus.METHOD_NOT_ALLOWED.value(), "请求方法不匹配，请检查请求方式!");
    }

    // 处理自定义异常
    @ExceptionHandler(CustomException.class)
    public Result handleCustomException(CustomException e) {
        return Result.error(e.getCode(), e.getMsg());
    }
    // 处理其他未处理的异常
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        e.printStackTrace();
        return Result.error(500, "服务器异常，请稍后重试！");
    }
}
